package com.ly.aidlpratice.local

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.ly.aidlpratice.R
import com.ly.aidlpratice.local.LocalService.LocalBinder
import com.ly.aidlpratice.util.logDebug

class LocalActivity : AppCompatActivity() {

    private val mTag: String by lazy { this::class.java.simpleName }

    private lateinit var mConnection: ServiceConnection
    private lateinit var mLocalService: LocalService
    private var mBoundCount = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_local)

        mConnection = object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                logDebug(mTag, "onServiceConnected[$name]")
                service?.also {
                    if (it is LocalBinder) {
                        mLocalService = it.getLocalService()
                    }
                }
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                logDebug(mTag, "onServiceDisconnected[$name]")
            }

        }

        val textView: TextView = findViewById(R.id.textView)
        findViewById<Button>(R.id.button2).setOnClickListener {
            if (mBoundCount > 0) {
                @SuppressLint("SetTextI18n")
                textView.text = "随机数字：${mLocalService.getRandomNumber()}"
            } else {
                Toast.makeText(this,"未绑定服务",Toast.LENGTH_SHORT).show()
            }
        }

        //第一次绑定成功后，后面的绑定是无效的；
        //并且，当前Activity销毁时，服务会自动解绑，回调onUnbind方法（如果仅仅使用了bindService方法，还会回调onDestroy方法）。
        findViewById<Button>(R.id.button3).setOnClickListener {
            mBoundCount++
            bindService(Intent(this, LocalService::class.java), mConnection, BIND_AUTO_CREATE)
            logDebug(mTag, "bindService mBoundCount=$mBoundCount")
        }

        findViewById<Button>(R.id.button4).setOnClickListener {
            if (mBoundCount > 0) {
                unbindService(mConnection)
                mBoundCount = 0
                logDebug(mTag, "unbindService mBoundCount=$mBoundCount")
            }
        }
    }
}